<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <a-spin :spinning="spinning">
        <a-form :form="headerForm" layout="inline" class="header-form">
          <a-form-item
            :label="item.fields === 'floor' ? '存放位置' : ''"
            v-for="item in headerOptions"
            :key="item.fields"
            v-show="item.show"
          >
            <a-select
              :options="item.options"
              :placeholder="`请选择${item.extra}`"
              allowClear
              v-decorator="[item.fields, { rules: [{ required: item.fields === 'floor', message: '请选择存放位置' }] }]"
              v-show="item.show"
            >
            </a-select>
            <span slot="extra" class="text-warning">{{ item.extra }}</span>
          </a-form-item>
          <a-row>
            <a-form-item label="操作">
              <y-button @click="handleHeaderCLick('edit')">修改</y-button>
              <y-button @click="handleHeaderCLick('new')">新建</y-button>
              <y-button @click="handleHeaderCLick('newCurrent')">新建当前</y-button>
            </a-form-item>
          </a-row>
        </a-form>
      </a-spin>
    </a-card>
    <transition enter-active-class="page-fade-in" leave-active-class="page-fade-out" mode="out-in">
      <a-card :bordered="false" class="m-t-16" v-if="show">
        <a-form :form="form" :labelCol="{ span: 2 }" :wrapperCol="{ span: 20 }">
          <a-form-item label="属性">
            <a-select v-decorator="['Depth']" :options="depthOptions" disabled> </a-select>
          </a-form-item>
          <a-form-item label="所属">
            <a-select v-decorator="['LID']" :options="LIDOptions" disabled> </a-select>
          </a-form-item>
          <a-form-item label="名称/标签">
            <a-input
              v-decorator="['Name', { rules: [{ required: true, message: '请输入名称/标签' }] }]"
              placeholder="请输入名称/标签"
            ></a-input>
          </a-form-item>
          <a-form-item label="地址">
            <a-input v-decorator="['Address', { initialValue: '' }]" placeholder="请输入地址"></a-input>
          </a-form-item>
        </a-form>
        <div class="text-center">
          <y-button type="primary" @click="handleSubmit" :loading="isSubmiting">{{
            $isEmpty(editElement) ? '添加' : '修改'
          }}</y-button>
          <y-button @click="handleCancel">取消</y-button>
        </div>
      </a-card>
    </transition>
  </page-header-wrapper>
</template>

<script>
import { getArDropList, postArchivesDepositary } from '@/api/fileManagement'
import lodash from 'lodash'
import moment from 'moment'
export default {
  data () {
    return {
      show: false,
      spinning: false,
      headerForm: this.$form.createForm(this, { name: 'headerForm', onValuesChange: this.onValuesChange }),
      form: this.$form.createForm(this, { name: 'form' }),
      headerOptions: [
        {
          fields: 'floor',
          options: [],
          extra: '楼',
          show: true
        },
        {
          fields: 'layer',
          options: [],
          extra: '层',
          show: false
        },
        {
          fields: 'room',
          options: [],
          extra: '室',
          show: false
        },
        {
          fields: 'cabinet',
          options: [],
          extra: '柜',
          show: false
        },
        {
          fields: 'cabinetLayer',
          options: [],
          extra: '柜层',
          show: false
        },
        {
          fields: 'box',
          options: [],
          extra: '盒',
          show: false
        }
      ],
      depthOptions: [
        {
          value: 1,
          label: '楼'
        },
        {
          value: 2,
          label: '层'
        },
        {
          value: 3,
          label: '室'
        },
        {
          value: 4,
          label: '柜'
        },
        {
          value: 5,
          label: '柜层'
        },
        {
          value: 6,
          label: '盒子'
        }
      ],
      LIDOptions: [],
      editElement: '',
      isSubmiting: false
    }
  },
  created () {
    this.fetchData('', 0)
  },
  methods: {
    fetchData (lid, index) {
      this.spinning = true
      getArDropList({
        lid
      })
        .then((res) => {
          this.headerOptions[index].options = res.map((e) => ({
            value: e.ID,
            label: e.NAME
          }))
          this.headerOptions[index].show = true
        })
        .finally(() => {
          this.spinning = false
        })
    },
    onValuesChange (props, values) {
      this.show = false
      this.form.resetFields()
      this.LIDOptions = []
      // 获取参数字段名称
      const fields = Object.keys(values).shift()
      this.fields = fields
      const value = values[fields]
      const current = this.headerOptions.findIndex((e) => e.fields === fields)
      // 不为空且不为盒加载下一级数据
      if (fields !== 'box') {
        this.clearAfterValue(current)
        if (!this.$isEmpty(value)) {
          this.fetchData(value, current + 1)
        }
      }
    },
    clearAfterValue (current) {
      // 清空后面选择与数据
      const index = current + 1
      const element = this.headerOptions[index]
      this.headerOptions[index].options = []
      this.headerOptions[index].show = false
      const obj = {}
      obj[element.fields] = undefined
      this.headerForm.setFieldsValue(obj)
    },
    handleHeaderCLick (type) {
      this.headerForm.validateFields((err, values) => {
        if (!err) {
          this.show = true
          values = lodash.omitBy(values, this.$isEmpty)
          const fieldsArr = Object.keys(values)
          const fields = fieldsArr.pop()
          const current = this.headerOptions.findIndex((e) => e.fields === fields)
          switch (type) {
            case 'edit':
              if (current === 0) {
                this.LIDOptions = [{ label: '顶级所属', value: '' }]
              } else {
                this.LIDOptions = this.headerOptions[current - 1].options
              }
              let Name = ''
              this.headerOptions[current].options.forEach((e) => {
                if (e.value === values[fields]) {
                  Name = e.label
                  this.editElement = e
                }
              })
              this.$nextTick(() => {
                this.form.setFieldsValue({
                  Depth: current + 1,
                  LID: current === 0 ? '' : values[fieldsArr[current - 1]],
                  Name
                })
              })
              break
            case 'new':
              this.editElement = {}
              if (current === 0) {
                this.LIDOptions = [{ label: '顶级所属', value: '' }]
              } else {
                this.LIDOptions = this.headerOptions[current - 1].options
              }
              this.$nextTick(() => {
                this.form.setFieldsValue({
                  Depth: current + 1,
                  LID: current === 0 ? '' : values[fieldsArr[current - 1]],
                  Name: ''
                })
              })
              break
            default:
              if (fields === 'box') {
                this.handleHeaderCLick('new')
              } else {
                this.editElement = {}
                this.LIDOptions = this.headerOptions[current].options
                this.$nextTick(() => {
                  this.form.setFieldsValue({
                    Depth: current + 2,
                    LID: values[fields],
                    Name: ''
                  })
                })
              }
              break
          }
        }
      })
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          const isAdd = this.$isEmpty(this.editElement)
          const { Depth } = values
          const ArchivesDepositaryModules = Object.assign(values, {
            ID: this.editElement.value || '',
            LID: Depth === 1 ? 0 : values.LID,
            CreateDate: isAdd ? moment().format('YYYY-MM-DD HH:mm:ss') : '',
            LastAlterDate: moment().format('YYYY-MM-DD HH:mm:ss')
          })
          this.isSubmiting = true
          postArchivesDepositary({
            State: isAdd ? 'add' : 'update',
            ArchivesDepositaryModules
          })
            .then((res) => {
              const { state } = res
              if (state === '200') {
                this.$message.success(isAdd ? '添加成功！' : '修改成功！')
                // 刷新数据
                if (Depth > 1) {
                  const upIndex = Depth - 2
                  const fields = this.headerOptions[upIndex].fields
                  const value = this.headerForm.getFieldValue(fields)
                  this.fetchData(value, Depth - 1)
                } else {
                  this.fetchData('', 0)
                }
              } else {
                this.$message.error(isAdd ? '添加失败，请重试！' : '修改失败，请重试！')
              }
            })
            .finally(() => {
              this.isSubmiting = false
            })
        }
      })
    },
    handleCancel () {
      this.form.resetFields()
      this.editElement = {}
      this.show = false
    }
  }
}
</script>
<style lang="less" scoped>
.header-form {
  /deep/ .ant-form-item-label {
    width: 100px;
  }
  /deep/ .ant-select {
    width: 150px;
  }
}
</style>
